#include "log.hpp"

void *recvAndPrint(void *args)
{
    int sockfd = *(int *)args;
    char buffer[1024];
    struct sockaddr_in temp;
    socklen_t len = sizeof(temp);
    while (1)
    {
        ssize_t s = recvfrom(sockfd, buffer, sizeof(buffer) - 1,
                             0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << buffer<< endl;
        }
    }
    return nullptr;
}
struct sockaddr_in server;

int main()
{
    string ip = "127.0.0.1";
    uint16_t port = 8080;
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    assert(sockfd > 0);

    bzero(&server, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    // 接收服务器信息的线程
    pthread_t t;
    pthread_create(&t, nullptr, recvAndPrint, (void *)&sockfd);

    // 往服务器发送信息
    string buffer;
    while (1)
    {
        cout << "Please Enter# ";
        std::getline(std::cin, buffer);
        sendto(sockfd, buffer.c_str(), buffer.size(),//首次调用时自动bind
               0, (struct sockaddr *)&server, sizeof(server));
    }
    close(sockfd);
    return 0;
}